package com.feige.handler;

import cn.hutool.core.util.StrUtil;
import com.feige.cache.CacheTemplate;
import com.feige.constant.Constants;
import com.feige.core.context.AppContext;
import com.feige.web.handler.HttpHandler;
import com.feige.web.result.SingleResult;
import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登出业务类
 * @author feige
 */
@AllArgsConstructor
public class TokenLogoutHandler implements LogoutSuccessHandler {


    private final CacheTemplate<String, Object> cacheTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getHeader(Constants.TOKEN_KEY);
        if (StrUtil.isNotBlank(token)) {
            Long loginUserId = AppContext.currentLoginUserId();
            if (loginUserId != null){
                //清空当前用户缓存中的权限数据
                cacheTemplate.del(Constants.LOGIN_USER_KEY + loginUserId);
                HttpHandler.renderString(response, SingleResult.success());
            }
        }
        HttpHandler.renderString(response, SingleResult.failure());
    }
}
